using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using IniParser;
using IniParser.Model;
using Newtonsoft.Json;
using static System.Collections.Specialized.BitVector32;
using static System.Runtime.InteropServices.JavaScript.JSType;
using static System.Windows.Forms.ListViewItem;

namespace 小说
{
    public partial class Form1 : Form
    {
        private Hashtable currentBook;
        private ArrayList arrlist;
        private readonly string bookRoot = "./files";
        private string savePath;
        private string fileName;
        private string configPath = "./config.ini";

        public Form1()
        {
            InitializeComponent();

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.moduleInit();
        }
        private void moduleInit()
        {
            this.treeViewInit();//书籍菜单初始化
            this.loadCustomControll();//阅读页面初始加载
            this.loadBook();//上次阅读数据初始化
        }
        private void loadCustomControll()
        {
            this.customControl11.ContextMenuStrip = this.contextMenuStrip1;
            //SelectionHangingIndent 属性的值仅适用于在第一行下方换行的段落中的行。
            //整数，该整数表示段落第一行文本的左边缘与同一段落中后面的行的左边缘之间的距离（以像素为单位）。
            this.customControl11.SelectionHangingIndent = 0;
            //整数，该整数表示控件的左边缘与文本的左边缘之间的距离（以像素为单位）
            this.customControl11.SelectionIndent = 20;
            //整数，该整数表示控件的右边缘与文本的右边缘之间的距离（以像素为单位）
            this.customControl11.SelectionRightIndent = 20;

            //右键菜单 字体 字号 初始化
            this.loadFontsFamily();//customControl11右键字体
            this.loadPt();//customControl11右键字号

            //customControll11字体字号初始化
            this.loadFonts();

        }
        private void loadFonts()
        {
            FileIniDataParser parser = new FileIniDataParser();
            IniData data = parser.ReadFile(this.configPath);
            //richTextBox1初始字体 字号
            this.customControl11.Font = new Font(data["system"]["font_name"], Convert.ToInt32(data["system"]["char_number"]));
        }
        //加载上次看的书籍
        private void loadBook(string bookName = "")
        {
            //读取书籍记录
            FileIniDataParser parser = new FileIniDataParser();
            IniData data = parser.ReadFile(this.configPath);
            string current_read;
            if (!bookName.Equals(""))
            {
                current_read = bookName;
            }
            else
            {
                current_read = data["system"]["current_read"];
            }
            if (current_read != null)
            {
                if (data[current_read] != null)
                {
                    try
                    {
                        string current_reads = data[current_read]["current_read"];
                        string[] indexs;
                        indexs = data[current_read]["index"].Split(",");

                        string filepath = this.bookRoot + "/" + current_read;
                        this.fileName = current_read;
                        string[] line = File.ReadAllLines(filepath);
                        this.listView1.Items.Clear();
                        this.listView1.BeginUpdate();
                        int index = 1;
                        int topItemIndex = 0;
                        foreach (string strings in line)
                        {
                            Book book = (Book)JsonConvert.DeserializeObject(strings, typeof(Book));
                            ListViewItem ch = new ListViewItem();
                            ch.Text = book.title;
                            ch.Tag = book;

                            //已读置灰
                            if (Array.IndexOf(indexs, index.ToString()) != -1)
                            {
                                ch.ForeColor = Color.Gray;
                            }
                            //正在读的章节
                            if (index.ToString() == current_reads)
                            {
                                topItemIndex = index - 1;
                                ch.BackColor = SystemColors.Highlight;
                                this.setRichBoxContent(book.title, book.content);
                            }
                            index++;

                            this.listView1.Items.Add(ch);
                        }
                        this.listView1.EndUpdate();
                        //设置滚动条
                        this.listView1.TopItem = this.listView1.Items[topItemIndex];
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("书籍出错！");
                    }
                }

            }
        }
        private void loadFontsFamily()
        {
            System.Drawing.Text.InstalledFontCollection fonts = new System.Drawing.Text.InstalledFontCollection();
            foreach (FontFamily font in fonts.Families)
            {
                bool result = Regex.IsMatch(font.Name, @"^[\u4e00-\u9fa5]{1,}$");
                if (result)
                {
                    ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem(font.Name.ToString());
                    toolStripMenuItem.Tag = font;
                    toolStripMenuItem.Click += new EventHandler(fontRToolStripMenuItem_Click);
                    this.fontToolStripMenuItem.DropDownItems.Add(toolStripMenuItem);
                }

            }
        }
        private void loadPt()
        {
            string[] stirngs = { "16", "18", "20", "22", "24", "26", "28", "30" };
            foreach (string stirn in stirngs)
            {
                ToolStripMenuItem ptSMI = new ToolStripMenuItem(stirn);
                ptSMI.Tag = stirn;
                ptSMI.Click += new EventHandler(ptRToolStripMenuItem_Click);
                this.ptToolStripMenuItem.DropDownItems.Add(ptSMI);
            }
        }
        private void fontRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (sender as ToolStripMenuItem).Checked = !(sender as ToolStripMenuItem).Checked;
            string fontname = sender.ToString();
            this.customControl11.Font = new Font(fontname, this.customControl11.Font.Size, FontStyle.Regular);
            //写入配置
            this.configWrite("system", "font_name", fontname);
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            this.clearRMenuSelected(tsmi, this.fontToolStripMenuItem);

        }
        //字号修改
        private void ptRToolStripMenuItem_Click(object sender, EventArgs e)
        {

            (sender as ToolStripMenuItem).Checked = !(sender as ToolStripMenuItem).Checked;
            string name = sender.ToString();
            int number = Convert.ToInt32(name);
            this.customControl11.Font = new Font(this.customControl11.Font.FontFamily, number, this.customControl11.Font.Style);
            //写入配置
            this.configWrite("system", "char_number", number.ToString());
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            this.clearRMenuSelected(tsmi, this.ptToolStripMenuItem);
        }
        //书籍菜单初始化
        private void treeViewInit()
        {
            string[] files = Directory.GetFiles(this.bookRoot+"/");
            string num = files.Length.ToString();

            TreeNode rootTree = new TreeNode("全部书籍(" + num + ")");
            this.treeView.Nodes.Add(rootTree);
            for (int i = 0; i < files.Length; i++)
            {
                //添加子节点
                files[i] = System.IO.Path.GetFileName(files[i]);
                TreeNode treeNode = new TreeNode(files[i]);
                //treeNode.Click += new EventHandler();
                rootTree.Nodes.Add(files[i]);
            }
            //全部展开
            this.treeView.ExpandAll();
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
            /*
            this.Close();仅仅是关闭当前窗口，若不是主窗体的话程序无法退出。
            Application.Exit();强制所有消息终止，退出所有的窗体。
            Application.ExitThread();强制终止调用线程上的所有消息。
            System.Environment.Exit(0);最彻底的退出方式，不管什么线程都可以被强制退出。
             */
        }
        //打开文件
        private void 打开NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //弹出选择框
            System.Windows.Forms.OpenFileDialog file = new System.Windows.Forms.OpenFileDialog();
            file.Filter = "*.txt|*.TXT";
            System.Windows.Forms.DialogResult result = file.ShowDialog();
            string path = ""; ;
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                path = file.FileName;
                this.openFileHandle(path);
            }
        }
        private void openFileHandle(string path)
        {
            //this.customControl11.Text = path;
            string FileLoad = path;
            string fileName = System.IO.Path.GetFileName(FileLoad);
            string savePath = this.bookRoot + "/" + fileName;
            this.fileName = fileName;
            this.savePath = savePath;

            //文件全部读取
            string[] fileContent = File.ReadAllLines(FileLoad);
            //按章节分割
            Task task = new Task(() =>
            {
                this.arrlist = this.bookSplit(fileContent);
                //写入文件
                this.writeFile(savePath);
            });
            task.Start();


        }
        private bool writeFile(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            foreach (Book book in this.arrlist)
            {
                string jsondata = JsonConvert.SerializeObject(book);
                sw.WriteLine(jsondata);
            }
            // sw.Write(jsondata);
            sw.Close();
            fs.Close();
            return true;

        }
        private ArrayList bookSplit(string[] fileContent)
        {
            ArrayList data = new ArrayList();
            //按章节分割
            string content = "";
            string subtitle = "序章";
            string upResult = "";
            int index = 0;
            this.toolStripProgressBar1.Value = 0;
            this.toolStripProgressBar1.Visible = true;
            //MessageBox.Show("task 执行了");
            this.listView1.BeginUpdate();
            foreach (string line in fileContent)
            {
                //匹配章节
                Match switchs = Regex.Match(line, "^\u7b2c.*\u7ae0");
                if (switchs.Success)
                {
                    //显示第一页
                    if (index == 0)
                    {
                        this.customControl11.Text = content;
                    }
                    index++;
                    //是否重复章节  存入book对象 加入hashtable
                    if (switchs.Value != upResult)
                    {
                        //content = content.Trim();
                        //存入book对象
                        Book book = this.createBookData(subtitle, content, index);
                        data.Add(book);
                        //添加listview项
                        ListViewItem ch = new ListViewItem();
                        ch.Text = subtitle;
                        ch.Tag = book;
                        this.listView1.Items.Add(ch);
                        subtitle = line.Trim();
                    }
                    //先显示20章
                    if (index == 20)
                    {
                        this.listView1.EndUpdate();
                        this.listView1.BeginUpdate();
                    }
                    content = "";
                    upResult = switchs.Value;
                }
                else
                {
                    content += "        " + line + "\n";
                }
            }
            //最后一章
            if (!content.Equals(""))
            {
                Book book = this.createBookData(subtitle, content, ++index);
                //存入book对象
                data.Add(book);
                //添加listview项
                ListViewItem ch = new ListViewItem();
                ch.Text = subtitle;
                this.listView1.Items.Add(ch);

            }
            this.listView1.EndUpdate();
            return data;
        }

        private Book createBookData(string subtitle, string content, int index)
        {
            Book book = new Book();
            book.title = subtitle;
            book.content = content;
            book.index = index;
            return book;
        }
        private void setRichBoxContent(string subtitle, string content)
        {
            string text = subtitle;
            text += "\n";
            text += "\n";
            this.customControl11.Text = text + content;
            //滚动条
            this.customControl11.SelectionStart = 0;
            this.customControl11.ScrollToCaret();
            this.customControl11.Text = text + content;
        }
        private void listView1_SelectedIndexChanged(object sender, MouseEventArgs e)
        {
            this.listViewSelectedChanged(this.listView1.SelectedItems[0]);
        }
        private void listViewSelectedChanged(ListViewItem currentLvi)
        {
            //MessageBox.Show(this.listView1.SelectedItems[0].Tag.ToString());
            try
            {
                //customControl11 内容  
                Book book = new Book();
                book = (Book)currentLvi.Tag;
                //标记已读
                book.is_read = true;
                //显示内容
                this.setRichBoxContent(book.title, book.content);
                //存储文件标记已读
                this.isRealSet(book.index);
            }
            catch (Exception ex)
            {

            }

            this.listView1.BeginUpdate();
            //清除所有高量
            int i = 0;
            foreach (ListViewItem lvi in this.listView1.Items)
            {
                lvi.BackColor = Color.White;
                //已读置灰
                Book book = (Book)lvi.Tag;
                try
                {
                    //book.is_read 一直报Object reference not set to an instance of an object 不知道为什么
                    if (book.is_read)
                    {
                        lvi.ForeColor = Color.Gray;
                        lvi.BackColor = Color.White;
                    }
                }
                catch (Exception)
                {

                }
            }
            //设置选中高量
            currentLvi.BackColor = SystemColors.Highlight;
            this.listView1.EndUpdate();
        }

        private void listView1_KeyDown(object sender, KeyEventArgs e)
        {
            ListViewItem lvi = this.listView1.SelectedItems[0];

            int count = this.listView1.Items.Count;
            int currentIndex = lvi.Index;
            //下一章
            if (e.KeyCode == Keys.Down)
            {
                if (count > currentIndex + 1)
                {
                    /*Book book = new Book();
                    book = (Book)this.listView1.Items[lvi.Index + 1].Tag;
                    this.setRichBoxContent(book.title,book.content);*/
                    this.listViewSelectedChanged(this.listView1.Items[lvi.Index + 1]);

                }
            }
            //上一章
            if (e.KeyCode == Keys.Up)
            {
                if (currentIndex > 0)
                {
                    /* Book book = new Book();
                     book = (Book)this.listView1.Items[lvi.Index - 1].Tag;
                     this.setRichBoxContent(book.title, book.content);*/
                    this.listViewSelectedChanged(this.listView1.Items[lvi.Index - 1]);
                }
            }

        }
        //已读数据写入
        private void isRealSet(int index)
        {
            this.configWrite(this.fileName, "index", index.ToString(), "a+");
            //正在读的章节
            this.configWrite(this.fileName, "current_read", index.ToString());
            this.configWrite("system", "current_read", this.fileName);
        }
        //写入配制
        private void configWrite(string section, string key, string value, string mode = "")
        {
            FileIniDataParser parser = new FileIniDataParser();
            IniData data = parser.ReadFile(this.configPath);
            string oldvalue = data[section][key];
            if (oldvalue != null)
            {
                switch (mode)
                {
                    //追加 会去重复
                    case "a+":
                        value = oldvalue + "," + value;
                        string[] val = value.Split(",");
                        string[] s = val.Distinct().ToArray();
                        value = string.Join(",", s);
                        break;
                    default:
                        break;
                }
                data[section][key] = value;
                parser.WriteFile(this.configPath, data);
            }
            else
            {
                data.Sections.AddSection(section);
                data[section].AddKey(key, value);
                parser.WriteFile(this.configPath, data);
            }
        }

        //左侧书籍点击事件
        private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.loadBook(e.Node.Text);
        }
        //richbox清除右键菜单选择
        private void clearRMenuSelected(ToolStripMenuItem cms, ToolStripMenuItem source)
        {
            foreach (ToolStripMenuItem item in source.DropDownItems)
            {
                if (item.Text.Equals(cms.Text))
                {
                    item.Checked = true;
                }
                else
                {
                    item.Checked = false;
                }
            }
        }

    }


    [Serializable]
    public class Book
    {
        public string title;//章节
        public string content;//内容
        public bool is_read = false;//是否已读 0未读 1已读
        public bool bookMark = false;//书签
        public int index;
    }
}
